package repository

import (
	"fmt"
	"log"
	"os"
	"time"

	pb "e-commerce/services/order-service/api/pb"

	"database/sql"

	_ "github.com/go-sql-driver/mysql"
	yaml "sigs.k8s.io/yaml/goyaml.v3"
)

type mysqlConfig struct {
	MySQL MySQLConfig `yaml:"mysql"`
}

type MySQLConfig struct {
	Database string `yaml:"database"`
	User     string `yaml:"user"`
	Password string `yaml:"password"`
	Host     string `yaml:"host"`
	Port     string `yaml:"port"`
}

type OrderRepository struct {
	db *sql.DB
}

func NewMySQLRepository(configPath string) *OrderRepository {
	yamlFile, err := os.ReadFile(configPath)
	if err != nil {
		log.Fatalf("读取配置文件失败: %v", err)
	}

	var cfg mysqlConfig
	err = yaml.Unmarshal(yamlFile, &cfg)
	if err != nil {
		log.Fatalf("解析配置文件失败: %v", err)
	}

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		cfg.MySQL.User, cfg.MySQL.Password, cfg.MySQL.Host, cfg.MySQL.Port, cfg.MySQL.Database)

	db, err := sql.Open("mysql", dsn)
	if err != nil {
		log.Fatalf("连接数据库失败: %v", err)
	}

	return &OrderRepository{db: db}
}

//手工创建order表
// CREATE TABLE `order` (
// 	`orderid` int(11) NOT NULL AUTO_INCREMENT,
// 	`userid` int(11) NOT NULL,
// 	`productid` varchar(255) NOT NULL,
// 	`quantity` int(11) NOT NULL,
// 	`status` varchar(255) NOT NULL,
// 	`created_at` datetime NOT NULL,
// 	`updated_at` datetime NOT NULL,
// 	PRIMARY KEY (`orderid`)
// ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

// order表插入数据
func (r *OrderRepository) CreateOrder(order *pb.Order) (int64, error) {
	//获取time.time格式的时间
	createtime := time.Now()
	updatetime := time.Now()
	if order.Orderid == 0 {
		result, err := r.db.Exec(
			"INSERT INTO orders (userid, productid, quantity, status, created_at, updated_at)"+
				"VALUES (?, ?, ?, ?, ?, ?)",
			order.UserId,
			order.ProductId,
			order.Quantity,
			"pending",
			createtime,
			updatetime,
		)
		if err != nil {
			return 0, err
		} else {
			//查询插入的orderid
			orderid, err := result.LastInsertId()
			if err != nil {
				return 0, err
			}
			return orderid, nil
		}
	} else {
		_, err := r.db.Exec(
			"INSERT INTO orders (orderid, userid, productid, quantity, status, created_at, updated_at)"+
				"VALUES (?, ?, ?, ?, ?, ?, ?)",
			order.Orderid,
			order.UserId,
			order.ProductId,
			order.Quantity,
			order.Status,
			createtime,
			updatetime,
		)
		if err != nil {
			return 0, err
		} else {
			return order.Orderid, nil
		}
	}
}

// order表查询数据
func (r *OrderRepository) GetOrder(orderid int64) (*pb.Order, error) {
	var order pb.Order
	var CreatedAt time.Time
	var UpdatedAt time.Time
	row := r.db.QueryRow("SELECT * FROM orders WHERE orderid = ?", orderid)
	err := row.Scan(&order.Orderid, &order.UserId, &order.ProductId, &order.Quantity, &order.Status, &CreatedAt, &UpdatedAt)
	if err != nil {
		return nil, err
	}
	order.CreatedAt = CreatedAt.Format("2006-01-02 15:04:05")
	order.UpdatedAt = UpdatedAt.Format("2006-01-02 15:04:05")
	return &order, nil
}

// order表更新数据
func (r *OrderRepository) UpdateOrder(order *pb.Order) error {
	_, err := r.db.Exec("UPDATE orders SET "+
		"userid = ?, productid = ?, quantity = ?, status = ?,  updated_at = ? WHERE orderid = ?",
		order.UserId,
		order.ProductId,
		order.Quantity,
		order.Status,
		time.Now(),
		order.Orderid,
	)
	if err != nil {
		return err
	}
	return nil
}

// order表删除数据
func (r *OrderRepository) DeleteOrder(orderid int64) error {
	_, err := r.db.Exec("DELETE FROM orders WHERE orderid = ?", orderid)
	if err != nil {
		return err
	}
	return nil
}

// order表查询批量数据
func (r *OrderRepository) ListOrdersByUserID(userID string) ([]*pb.Order, error) {
	var orders []*pb.Order
	rows, err := r.db.Query("SELECT * FROM orders WHERE userid = ?", userID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	for rows.Next() {
		var order pb.Order
		var CreatedAt time.Time
		var UpdatedAt time.Time
		err := rows.Scan(&order.Orderid, &order.UserId, &order.ProductId, &order.Quantity, &order.Status, &CreatedAt, &UpdatedAt)
		if err != nil {
			return nil, err
		}
		order.CreatedAt = CreatedAt.Format("2006-01-02 15:04:05")
		order.UpdatedAt = UpdatedAt.Format("2006-01-02 15:04:05")
		orders = append(orders, &order)
	}
	return orders, nil
}

// order表更新数据
func (r *OrderRepository) UpdateOrderStatus(orderID int64, status string) error {
	_, err := r.db.Exec("UPDATE orders SET status = ?, updated_at = ? WHERE orderid = ?",
		status,
		time.Now(),
		orderID,
	)
	if err != nil {
		return err
	}
	return nil
}

// order表更新数据
func (r *OrderRepository) MarkOrderPaid(orderID int64, success bool) error {
	if success {
		_, err := r.db.Exec("UPDATE orders SET status = ?, updated_at = ? WHERE orderid = ?",
			"paid",
			time.Now(),
			orderID,
		)
		if err != nil {
			return err
		}
		return nil
	} else {
		_, err := r.db.Exec("UPDATE orders SET status = ?, updated_at = ? WHERE orderid = ?",
			"failed",
			time.Now(),
			orderID,
		)
		if err != nil {
			return err
		}
		return nil
	}
}

func (r *OrderRepository) QueryOrderStatus(orderID int64) (string, error) {
	var status string
	err := r.db.QueryRow("SELECT status FROM orders WHERE orderid = ?", orderID).Scan(&status)
	if err != nil {
		return "", err
	}
	return status, nil
}
